package com.skyline.courier.rpc;

import org.apache.commons.lang.reflect.MethodUtils;

import com.skyline.courier.net.Handler;
import com.skyline.courier.rpc.exception.NoSuchServiceException;
import com.skyline.courier.rpc.pojo.RequestBean;

public class RpcMsgHandler implements Handler {
	private ServiceRepository repository;
	
	public void setRepository(ServiceRepository repository) {
		this.repository = repository;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <I, O> O process(I input) throws Exception {
		if(input instanceof RequestBean) {
			RequestBean request = (RequestBean) input;
			
			String serviceName = request.getServiceName();
			String methodName = request.getMethodName();
			Object service = repository.getService(serviceName);
			
			if(service != null) {
				Object[] args = request.getArgs();
				// 调用服务
				Object retObj =  MethodUtils.invokeMethod(service, methodName, args);
				// 设置调用结果返回值
				return (O) retObj;
			} else {
				NoSuchServiceException ex = new NoSuchServiceException("服务[" + serviceName + "]不存在");
				throw ex;
			}			
			
		} else {
			return null;
		}
	}

}
